<template>
    <div class="fillcontain">
        <head-top></head-top>
        <div class="table_container">
            <el-button type="primary" @click="addTaoCan" class="el-icon-circle-plus" circle>新增</el-button>
            <el-table
                :data="tableData"
                @expand='expand'
                :expand-row-keys='expendRow'
                :row-key="row => row.index"
                style="width: 100%">
                <el-table-column
                  type="index"
                  width="80">
                </el-table-column>
                <el-table-column
                  property="image_url"
                  label="套餐Logo"
                  width="120"
                  align='center'>
                  <template slot-scope="scope">
                    <img  :src="scope.row.image_url" alt="" style="width: 55px;height: 50px">
                  </template>
                </el-table-column>
                <el-table-column
                  label="套餐名称"
                  prop="name"
                  align='center'
                  width="120">
                </el-table-column>
                <el-table-column
                  label="套餐价格(元)"
                  prop="money"
                  align='center'
                  width="120">
                </el-table-column>
                <el-table-column
                  label="套餐流量"
                  prop="pv"
                  align='center'
                  width="120">
                </el-table-column>
                <el-table-column
                  label="套餐详情"
                  prop="remark"
                  align='center'>
                </el-table-column>
                <el-table-column label="操作" width="140" align='center'>
                  <template slot-scope="scope">
                    <el-button
                      size="small"
                      @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="deleteTaocan(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
            <div class="Pagination">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-size="20"
                  layout="total, prev, pager, next"
                  :total="count">
                </el-pagination>
            </div>
            <el-dialog title="编辑套餐信息" v-model="dialogFormVisible">
                <el-form :model="selectTable">
                    <el-form-item label="套餐名称" label-width="100px">
                        <el-input v-model="selectTable.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="套餐价格" label-width="100px">
                        <el-input v-model="selectTable.money" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐流量" label-width="100px">
                        <el-input v-model="selectTable.pv" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐详情" label-width="100px">
                        <el-input v-model="selectTable.remark" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐图标" label-width="100px">
                        <!-- <el-input v-model="selectTable.pv" :min="0" :max="100"></el-input> -->
                        <img  :src="selectTable.image_url" alt="" style="width: 55px;height: 50px">
					</el-form-item>
                </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateTaoCan">确 定</el-button>
              </div>
            </el-dialog>

            <el-dialog title="确定删除该套餐信息?" v-model="deleteFormVisible">
              <div slot="footer" class="dialog-footer">
                <el-button @click="deleteFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteTaoCan">确 定</el-button>
              </div>
            </el-dialog>


            <el-dialog title="新增套餐" v-model="specsFormVisible">
			  	<el-form :rules="specsFormrules" :model="specsForm">
				    <el-form-item label="套餐名称" label-width="100px">
                        <el-input v-model="specsForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="套餐价格" label-width="100px">
                        <el-input v-model="specsForm.money" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐详情" label-width="100px">
                        <el-input v-model="specsForm.remark" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐流量" label-width="100px">
                        <el-input v-model="specsForm.pv" :min="0" :max="100"></el-input>
					</el-form-item>
                    <el-form-item label="套餐图标" label-width="100px">
                        <!-- <el-input v-model="specsForm.image_url" :min="0" :max="100"></el-input> -->
                        <img  :src="specsForm.image_url" alt="" style="width: 80px;height: 50px">
					</el-form-item>
			  	</el-form>
			  <div slot="footer" class="dialog-footer">
			    <el-button @click="specsFormVisible = false">取 消</el-button>
			    <el-button type="primary" @click="addNewTaoCan">确 定</el-button>
			  </div>
			</el-dialog>
        </div>
    </div>
</template>

<script>
    import headTop from '../components/headTop'
    import {baseUrl, baseImgPath} from '@/config/env'
    import {getTaocans, getTaocanCount,deleteTaoCan, addNewTaoCan,rgetMenu, updateTaoCan, deleteFood, getResturantDetail, getMenuById} from '@/api/getData'
    export default {
        data(){
            return {
                baseUrl,
                baseImgPath,
                restaurant_id: null,
                city: {},
                offset: 0,
                limit: 30,
                count: 0,
                tableData: [],
                currentPage: 1,
                selectTable: {},
                deleteTable:{},
                dialogFormVisible: false,
                menuOptions: [],
                selectMenu: {},
                status :0,
                trade_id:'',
                selectIndex: null,
                specsForm: {'image_url':'http://pddapi.taotetui.com/upload/1543213505841_97.jpg','money':-1,'pv':0},
                specsFormrules: {
		        	specs: [
						{ required: true, message: '请输入规格', trigger: 'blur' },
					],
		        },
                specsFormVisible: false,
                deleteFormVisible:false,
                expendRow: [],
            }
        },
        created(){
        	this.restaurant_id = this.$route.query.restaurant_id;
            this.initData();
        },
        computed: {
        	specs: function (){
        		let specs = [];
        		if (this.selectTable.specfoods) {
	        		this.selectTable.specfoods.forEach(item => {
	        			specs.push({
	        				specs: item.specs_name,
	        				packing_fee: item.packing_fee,
	        				price: item.price,
	        			})
	        		})
        		}
        		return specs
        	}
        },
    	components: {
    		headTop,
    	},
        methods: {
            async initData(){
                try{
                    const countData = await getTaocanCount();
                    if (countData.code == 200) {
                        this.count = countData.data;
                    }else{
                        throw new Error('获取数据失败');
                    }
                    this.getFoods();
                }catch(err){
                    console.log('获取数据失败', err);
                }
            },
            async getMenu(){
            	this.menuOptions = [];
                try{
                    const menu = await getMenu({restaurant_id: this.selectTable.restaurant_id, allMenu: true});
                    menu.forEach((item, index) => {
                        this.menuOptions.push({
                        	label: item.name,
                        	value: item.id,
                        	index,
                        })
                    })
                }catch(err){
                    console.log('获取食品种类失败', err);
                }
            },
            async getFoods(){
                const Foods = await getTaocans(this.offset, this.limit);
                this.tableData = [];
                Foods.data.forEach((item, index) => {
                    const tableData = {};
                    tableData.money = item.money/100;
                    tableData.name = item.name;
                    tableData.remark = item.remark;
                    tableData.image_url = item.image_url;
                    tableData.id = item.id;
                    tableData.pv = item.pv;
                    this.tableData.push(tableData);
                })
            },
            tableRowClassName(row, index) {
		        if (index === 1) {
		        	return 'info-row';
		        } else if (index === 3) {
		        	return 'positive-row';
		        }
		        return '';
		    },
		    addTaoCan(){
				//this.specsForm=row
                this.specsFormVisible = true;
			},
			deleteTaocan(row){
                this.deleteFormVisible = true;
                this.deleteTable = row;
			},
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.offset = (val - 1)*this.limit;
                this.getFoods()
            },
            expand(row, status){
            	if (status) {
            		this.getSelectItemData(row)
            	}else{
                    const index = this.expendRow.indexOf(row.index);
                    this.expendRow.splice(index, 1)
                }
            },
            handleEdit(row) {
                //this.getSelectItemData(row, 'edit')
                this.selectTable = row
                this.dialogFormVisible = true;
            },
            async getSelectItemData(row, type){
            	const restaurant = await getResturantDetail(row.restaurant_id);
            	const category = await getMenuById(row.category_id)
                this.selectTable = {...row, ...{restaurant_name: restaurant.name, restaurant_address: restaurant.address, category_name: category.name}};

                this.selectMenu = {label: category.name, value: row.category_id}
                this.tableData.splice(row.index, 1, {...this.selectTable});
                this.$nextTick(() => {
                    this.expendRow.push(row.index);
                })
                if (type == 'edit' && this.restaurant_id != row.restaurant_id) {
                	this.getMenu();
                }
            },
            handleSelect(index){
                this.status = index;
                //alert(this.status)
            	//this.selectMenu = this.menuOptions[index];
            },
            async handleDelete(index, row) {
                try{
                    const res = await deleteFood(row.item_id);
                    if (res.status == 1) {
                        this.$message({
                            type: 'success',
                            message: '删除食品成功'
                        });
                        this.tableData.splice(index, 1);
                    }else{
                        throw new Error(res.message)
                    }
                }catch(err){
                    this.$message({
                        type: 'error',
                        message: err.message
                    });
                    console.log('删除食品失败')
                }
            },
            handleServiceAvatarScucess(res, file) {
                if (res.status == 1) {
                    this.selectTable.image_path = res.image_path;
                }else{
                    this.$message.error('上传图片失败！');
                }
            },
            beforeAvatarUpload(file) {
                const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isRightType) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isRightType && isLt2M;
            },
            async updateTaoCan(){
                this.dialogFormVisible = false;
                //alert(this.selectTable.name)
                try{
                    const tmp = {'money':this.selectTable.money*100,'image_url':this.selectTable.image_url,'name':this.selectTable.name,'remark':this.selectTable.remark,'pv':this.selectTable.pv}
                    const res = await updateTaoCan(this.selectTable.id,tmp)
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '更新套餐状态成功'
                        });
                        this.getFoods();
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.message
                        });
                    }
                }catch(err){
                    console.log('更新套餐信息失败', err);
                }
            },
            async addNewTaoCan(){
                this.specsFormVisible = false;
                try{
                    const tmp = {'money':this.specsForm.money*100,'image_url':this.specsForm.image_url,'name':this.specsForm.name,'remark':this.specsForm.remark,'pv':this.specsForm.pv}
                    const res = await addNewTaoCan(tmp)
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '新增套餐状态成功'
                        });
                        this.getFoods();
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.message
                        });
                    }
                }catch(err){
                    console.log('新增套餐信息失败', err);
                }
            },
            async deleteTaoCan(){
                this.deleteFormVisible = false;
                //alert(this.deleteTable.id);
                try{
                    const res = await deleteTaoCan(this.deleteTable.id)
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '删除套餐状态成功'
                        });
                        this.getFoods();
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.message
                        });
                    }
                }catch(err){
                    console.log('删除套餐信息失败', err);
                }
            },
        },
    }
</script>

<style lang="less">
	@import '../style/mixin';
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .table_container{
        padding: 20px;
    }
    .Pagination{
        display: flex;
        justify-content: flex-start;
        margin-top: 8px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }
    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
</style>
